import { Link as RouterLink, LinkProps, useLocation } from "react-router-dom";
import { forwardRef } from "react";
import { activeTabKeyAtom, workspaceTabsAtom } from "../WorkspaceTabs";
import { useAtomCallback } from "jotai/utils";

export const Link = forwardRef<HTMLAnchorElement, LinkProps>((props, ref) => {
  const { pathname } = useLocation();
  const isWorkspace = pathname === "/homepage/index";
  const onLinkWorkspaceTab = useAtomCallback((get, set, href: string) => {
    const activeTab = get(activeTabKeyAtom);
    if (!activeTab) return;
    set(workspaceTabsAtom, (tabs) => {
      return tabs.map((tab) => {
        if (tab.key === activeTab) {
          return {
            ...tab,
            path: href,
          };
        }
        return tab;
      });
    });
  });

  return (
    <RouterLink
      {...props}
      onClick={(e) => {
        if (isWorkspace) {
          e.preventDefault();
          if (props.to !== "#") {
            const href =
              typeof props.to === "string"
                ? props.to
                : `${props.to.pathname}?${new URLSearchParams(
                    props.to.search,
                  ).toString()}`;
            onLinkWorkspaceTab(href);
          }
        }
        props.onClick?.(e);
      }}
      ref={ref}
    />
  );
});
